/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
package com.openatc.configserver.controller;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.openatc.comm.common.CommClient;
import com.openatc.comm.data.MessageData;
import com.openatc.core.common.IErrorEnumImplOuter;
import com.openatc.core.model.RESTRet;
import com.openatc.core.model.RESTRetBase;
import com.openatc.core.util.FileUtil;
import com.openatc.core.util.RESTRetUtils;
import com.openatc.model.model.AscsBaseModel;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.logging.Logger;

import static com.openatc.comm.common.AgentInfoType.Secretkey_Update;
import static com.openatc.comm.common.CommunicationType.OPERATOER_TYPE_GET_REQUEST;
import static com.openatc.core.common.IErrorEnumImplOuter.E_8014;


@Path("/")
public class DeviceController {

    protected CommClient commClient = new CommClient();
    public static AscsBaseModel ascsBaseModel = new AscsBaseModel();

    private static Logger logger = Logger.getLogger(DeviceController.class.toString());

    static Gson gson = new Gson();

    private static String secretkeypath = "../config/key";

    static {
        ascsBaseModel.setId(0);
        ascsBaseModel.setThirdplatformid("0");
        ascsBaseModel.setProtocol("ocp");
        ascsBaseModel.setType("asc");
        JsonObject json = new JsonObject();
        json.addProperty("ip","localhost");
        json.addProperty("port","8880");
        ascsBaseModel.setJsonparam(json);
        ascsBaseModel.setAuth(0);
        try {
            String str = FileUtil.readString(secretkeypath);
            JsonObject jsonObject = gson.fromJson(str,JsonObject.class);
            String siteid = jsonObject.get("id").getAsString();
            String secretkey = jsonObject.get("secretkey").getAsString();
            ascsBaseModel.setThirdplatformid(siteid);
            ascsBaseModel.setSecretkey(secretkey);
            ascsBaseModel.setAuth(2);

        }catch (Exception e){
            logger.warning("Read SecretFile Error ! :" + e.getMessage() );
        }


    }

    public DeviceController() {
    }

    @Path("devs")
    @POST
    @Consumes(MediaType.APPLICATION_JSON) // 声明传入参数是json格式
    @Produces(MediaType.APPLICATION_JSON)
    public RESTRetBase insertDev(AscsBaseModel ascs) {
//        if(ascs.getAuth() == null)
//            ascs.setAuth(2);
        if(ascs.getProtocol() == null)
            ascs.setProtocol("ocp");
        ascsBaseModel.setProtocol(ascs.getProtocol() );
        ascsBaseModel.setJsonparam(ascs.getJsonparam() );
        if(ascs.getAuth() != null)
            ascsBaseModel.setAuth(ascs.getAuth() );

        logger.warning("insert device :" + ascs);
        return RESTRetUtils.successObj(ascsBaseModel);
    }

    @Path("devs/{id}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public RESTRetBase getDevs(@PathParam("id") int id) {
        return RESTRetUtils.successObj(ascsBaseModel);
    }

    @Path("devs/message")
    @POST
    @Consumes(MediaType.APPLICATION_JSON) // 声明传入参数是json格式
    @Produces(MediaType.APPLICATION_JSON)
    public RESTRet postDevsMessage(MessageData requestData) {

        return commClient.devMessage(requestData,ascsBaseModel);
    }

    /**
     * 获取路口渠化图
     * @param agentid
     * @return
     */
    @Path(value = "devs/channelizatonchart/{agentid}")
    @GET
    public RESTRet getIntChannelizationChart(@PathParam("agentid") String agentid){
        return RESTRetUtils.errorObj(false, IErrorEnumImplOuter.E_2002);
    }

    /**
     * 更新密钥，并通知信号机更新
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Path("/devs/auth/update")
    @POST
    @Consumes(MediaType.APPLICATION_JSON) // 声明传入参数是json格式
    @Produces(MediaType.APPLICATION_JSON)
    public RESTRet updateDevAuth( JsonObject jsonObject) throws Exception {
        String siteid = jsonObject.get("id").getAsString();
        String secretkey = jsonObject.get("secretkey").getAsString();
        if(secretkey.isEmpty())
            return RESTRetUtils.errorObj(false,E_8014);

        // 通知信号机更新系统
        MessageData md = new MessageData();
        ascsBaseModel.setThirdplatformid(siteid);
        md.setOperation(OPERATOER_TYPE_GET_REQUEST);
        md.setInfotype(Secretkey_Update.toString());
        RESTRet ret = new CommClient().devMessage(md,ascsBaseModel);
        if(ret.isSuccess()){
            FileUtil.writeString( secretkeypath ,gson.toJson(jsonObject));

            ascsBaseModel.setSecretkey(secretkey);
            ascsBaseModel.setAuth(2);
        }

        return ret;
    }
}